package com.golang.codegen.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.golang.codegen.entity.GenConfig;
import com.golang.codegen.service.SysGeneratorService;
import com.golang.codegen.util.PageUtils;
import com.golang.codegen.util.Query;
import com.golang.codegen.util.R;

import cn.hutool.core.io.IoUtil;
import lombok.AllArgsConstructor;

/**
 * 代码生成器
 *
 * @author lzdn
 * @date 2018-07-30
 */
@RestController
@AllArgsConstructor
@RequestMapping("/generator")
public class SysGeneratorController {
	private final SysGeneratorService sysGeneratorService;

	/**
	 * 列表
	 *
	 * @param params
	 *            参数集
	 * @return 数据库表
	 */
	@GetMapping("/list")
	public R list(@RequestParam Map<String, Object> params) {
		Query query = new Query(params);
		query.setRecords(sysGeneratorService.queryPage(query));
		PageUtils pageUtils = new PageUtils(query);
		return R.ok().put("page", pageUtils);
	}

	/**
	 * 生成代码
	 */

	@GetMapping("/code")
	public void code(@RequestParam Map<String, Object> params, HttpServletResponse response) throws IOException {
		String[] tableNames = new String[] {};
		tableNames = JSON.parseArray(String.valueOf(params.getOrDefault("tables", ""))).toArray(tableNames);
		GenConfig genConfig = new GenConfig();
		genConfig.setTableNames(tableNames);
		byte[] data = sysGeneratorService.generatorCode(genConfig);
		response.reset();
		response.setHeader("Content-Disposition",
				String.format("attachment; filename=%s.zip", "golangCode"));
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);

	}

}
